package com.guchenbo.study.xml;

import com.guchenbo.study.xml.service.BenzLogo;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * @Author guchenbo
 * @Date 2019/4/5.
 */
public class ApplicationContextTest {

    public static void main(String[] args) {
        ApplicationContext context;
        //        beanFactory = bindByCode();
        context = bindByXml();

        CarProvider provider = (CarProvider) context.getBean("carProvider");
        String logo = provider.logo();
        System.out.println(logo);
    }

    /**
     * xml配置文件形式，从xml中启动
     *
     * @param
     */
    private static ApplicationContext bindByXml() {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("application.xml");
        return context;

        //
        //return new XmlBeanFactory(new ClassPathResource("application.xml"));
    }

    /**
     * 通过编码形式，注册bean和绑定bean之间的依赖
     * 注册到ioc的其实是bean definition
     *
     * @param
     */
    private static BeanFactory bindByCode() {
        DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
        // 定义bean
        BeanDefinitionBuilder benzLogoBuilder = BeanDefinitionBuilder.genericBeanDefinition(BenzLogo.class);
        BeanDefinition benzDefinition = benzLogoBuilder.getBeanDefinition();

        BeanDefinitionBuilder carProviderBuilder = BeanDefinitionBuilder.genericBeanDefinition(CarProvider.class);
        BeanDefinition carProviderDefinition = carProviderBuilder.getBeanDefinition();

        // 设置对象依赖
        carProviderBuilder.addPropertyValue("carLogo", benzDefinition);

        // 注册bean
        beanFactory.registerBeanDefinition("benzLogo", benzDefinition);
        beanFactory.registerBeanDefinition("carProvider", carProviderDefinition);
        return beanFactory;
    }

}
